﻿using System;
using System.Text;

using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Web;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Forms;

namespace MyTools
{

    class TokenInfo
    {
        public string message { get; set; }
        public string messageType { get; set; }
        public string status { get; set; }
        public string token { get; set; }
    }

    public class Req
    {
        public string url { get; set; }
        public string param { get; set; }
        public string method { get; set; }
        public string contType { get; set; }
    }

    public class TxtTool
    {
        private static string TXT_PATH = "req.txt";

        /// <summary>
        /// 从文本文件中，加载请求连接和请求参数
        /// </summary>
        /// <returns></returns>
        internal static List<Req> LoadReqFromTxt()
        {
            List<Req> lst = new List<Req>();
            try
            {
                List<string> lines = ReadTxt2Lines();
                foreach(string line in lines)
                {
                    Req req = line2Req(line);
                    if(req != null)
                    {
                        lst.Add(req);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("加载文件出错");
            }
            return lst;
        }

        public static Boolean SaveReq2Text(Req req)
        {
            Boolean flag = false;
            if (!File.Exists(TXT_PATH))
            {
                // 创建、写入
                FileStream fs = new FileStream(TXT_PATH, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("{0},{1}", req.url, req.param);
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
                flag = true;
            }
            else
            {
                // 创建、写入
                FileStream fs = new FileStream(TXT_PATH, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("{0},{1}", req.url, req.param);
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
                flag = true;
            }
            return flag;
        }

        /// <summary>
        /// 读取文本文件中的每一行数据，放到一个list集合中
        /// </summary>
        /// <returns></returns>
        static List<string> ReadTxt2Lines()
        {
            List<string> lines = new List<string>();
            try
            {
                if (File.Exists(TXT_PATH))
                {
                    StreamReader sr = new StreamReader(TXT_PATH);
                    // 读第一行数据
                    string line = sr.ReadLine();
                    while (line != null && line.Length > 0)
                    {
                        lines.Add(line);
                        // 读下一行
                        line = sr.ReadLine();
                    }
                    sr.Close();
                }
                else
                {
                    StreamWriter streamWriter = File.CreateText(TXT_PATH);
                    streamWriter.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("读取文件中的数据报错");
            }
            return lines;
        }

        /// <summary>
        /// 删除文本文件中的请求连接和参数
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        internal static bool deleteReqFromTxt(int index)
        {
            Boolean b = false;

            if (File.Exists(TXT_PATH) && index >= 0)
            {
                List<string> lines = ReadTxt2Lines();
                if (lines.Count > 0)
                {
                    File.Delete(TXT_PATH);
                    lines.RemoveAt(index);
                    foreach (string line in lines)
                    {
                        Req req = line2Req(line);
                        if (req != null)
                        {
                            SaveReq2Text(req);
                        }
                    }
                }

            }
            return b;
        }

        /// <summary>
        /// 将文本文件中的请求记录转换为req对象
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        private static Req line2Req(string line)
        {
            string[] vs = line.Split(',');
            if (vs.Length >= 2)
            {
                Req req = new Req()
                {
                    url = vs[0],
                    param = vs[1],
                    method = "POST",
                    contType = "FORM"
                };
                return req;
            }
            return null;
        }
    }

    public class JsonTool
    {

        public static string FormatJsonStr(string json)
        {
            string retStr = "";
            if (json.Length == 0)
            {
                return retStr;
            }

            try
            {
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(json);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Formatting.Indented,
                        Indentation = 4,//缩进字符数
                        IndentChar = ' '//缩进字符
                    };
                    serializer.Serialize(jsonWriter, obj);
                    retStr = textWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误的JSON");
            }
            return retStr;
        }
        /// <summary>
        /// 对form参数进行格式化
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        internal static string FormatFormParam(string param)
        {
            string retStr = "";
            if (param.Length == 0)
            {
                return retStr;
            }

            string[] pas = param.Split('&');
            foreach(string pa in pas)
            {
                if (pa.Length > 0)
                {
                    retStr += "&"+pa + "\r\n";
                }
            }
            return retStr;
        }

        /// <summary>
        /// TextBox的内容格式化成form表单参数
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        internal static string Text2FormParam(string text)
        {
            string retStr = "";
            if (text.Length == 0)
            {
                return retStr;
            }

            string[] pas = text.Split('&');
            foreach (string pa in pas)
            {
                if (pa.Length > 0)
                {
                    string temp = pa;
                    // "userName=ex_dengcc2\r\n"
                    if (pa.EndsWith("\r\n"))
                    {
                       temp = pa.Substring(0,pa.Length-2);
                    }
                    retStr += "&" + temp;
                }
            }
            return retStr;
        }
    }
    public class RestfullRequest
    {

        private static string TXT_PATH = "req.txt";

        public static string LimsPostToken(string url,string name,string funcName)
        {
            string method = "post";
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_",name);
            header.Add("__TokenAuthorization_Function_", funcName);
            return Request(url, "post", "application/x-www-form-urlencoded", null, header);
        }

        public static string LimsPostForm(string url,string name,//
            string funcName,string token,string data)//
        {
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_", name);
            header.Add("__TokenAuthorization_Function_", funcName);
            header.Add("__TokenAuthorization_UID_", token);
            return Request(url, "post", "application/x-www-form-urlencoded", data, header);
        }

        internal static List<Req> LoadReqFromTxt()
        {
            String line;
            List<Req> lst = new List<Req>();
            try
            {
                if(File.Exists(TXT_PATH))
                {
                    StreamReader sr = new StreamReader(TXT_PATH);
                    line = sr.ReadLine();
                    while (line != null && line.Length > 0)
                    {
                        Req req = line2Req(line);
                        lst.Add(req);
                        line = sr.ReadLine();
                    }
                    sr.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("加载文件出错");
            }
            return lst;
        }

        public static string LimsPostFormUseToken(//
            string tokenUrl,string url, string name,//
            string funcName, string data)//
        {
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_", name);
            header.Add("__TokenAuthorization_Function_", funcName);
            string tokenStr = LimsPostToken(tokenUrl, name, funcName);
            TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(tokenStr);
            header.Add("__TokenAuthorization_UID_", tokenInfo.token);

            data += "&__TokenAuthorization_UserName_=" + name;

            return Request(url, "post", "application/x-www-form-urlencoded", data, header);
        }

        public static string LimsPostJsonUseToken(//
            string tokenUrl, string url, string name,//
            string funcName, string data)//
        {
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_", name);
            header.Add("__TokenAuthorization_Function_", funcName);
            string tokenStr = LimsPostToken(tokenUrl, name, funcName);
            TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(tokenStr);
            header.Add("__TokenAuthorization_UID_", tokenInfo.token);

            data += "&__TokenAuthorization_UserName_="+name;

            return Request(url, "post", "application/json", data, header);
        }

        public static string LimsPostForm(string url,// 
            string name, string funcName, //
            string token, NameValueCollection postData)//
        {
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_", name);
            header.Add("__TokenAuthorization_Function_", funcName);
            header.Add("__TokenAuthorization_UID_", token);

            postData.Add("__TokenAuthorization_UserName_", name);
            postData.Add("__TokenAuthorization_Function_", funcName);
            postData.Add("__TokenAuthorization_UID_", token);

            StringBuilder stringBuilder = new StringBuilder();
            foreach (string key in postData.Keys)
            {
                stringBuilder.AppendFormat("&{0}={1}", key, postData.Get(key));
            }
            return Request(url, "post", "application/x-www-form-urlencoded", stringBuilder.ToString(), header);
        }

        public static Boolean SaveReq2Text(Req req)
        {
            Boolean flag = false;
            if (!File.Exists(TXT_PATH))
            {
                // 创建、写入
                FileStream fs = new FileStream(TXT_PATH, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("{0},{1}",req.url,req.param);
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
                flag = true;
            }
            else
            {
                // 创建、写入
                FileStream fs = new FileStream(TXT_PATH, FileMode.Append,FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("{0},{1}", req.url, req.param);
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
                flag = true;
            }
            return flag;
        }

        public static string LimsPostFormUseToken(string tokenUrl, string url, 
            string name, string funcName, //
            NameValueCollection postData = null)//
        {
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_", name);
            header.Add("__TokenAuthorization_Function_", funcName);
            string tokenStr = LimsPostToken(tokenUrl, name, funcName);
            TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(tokenStr);
            header.Add("__TokenAuthorization_UID_", tokenInfo.token);

            postData.Add("__TokenAuthorization_UserName_", name);
            postData.Add("__TokenAuthorization_Function_", funcName);
            postData.Add("__TokenAuthorization_UID_", tokenInfo.token);

            StringBuilder stringBuilder = new StringBuilder();
            if (postData != null)
            {
                foreach (string key in postData.Keys)
                {
                    stringBuilder.AppendFormat("&{0}={1}", key, postData.Get(key));
                }
            }
            return Request(url, "post", "application/x-www-form-urlencoded", stringBuilder.ToString(), header);
        }

        public static string LimsPostJsonUseToken(string tokenUrl, string url,
           string name, string funcName, //
           NameValueCollection postData = null)//
        {
            NameValueCollection header = new NameValueCollection();
            header.Add("__TokenAuthorization_UserName_", name);
            header.Add("__TokenAuthorization_Function_", funcName);
            string tokenStr = LimsPostToken(tokenUrl, name, funcName);
            TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(tokenStr);
            header.Add("__TokenAuthorization_UID_", tokenInfo.token);

            StringBuilder stringBuilder = new StringBuilder();
            if (postData != null)
            {
                foreach (string key in postData.Keys)
                {
                    stringBuilder.AppendFormat("&{0}={1}", key, postData.Get(key));
                }
            }
            return Request(url, "post", "application/json", stringBuilder.ToString(), header);
        }

        private static string Request(string url, string method, 
            string contentType, string data, //
            NameValueCollection header = null, //
            NetworkCredential credential = null,//
            string proxyAddress = null, //
            Encoding responseEncoding = null)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            if (url.StartsWith("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidate);//验证服务器证书回调自动验证
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            }
            request.Method = method;
            if (!string.IsNullOrEmpty(contentType))
                request.ContentType = contentType;
            if (header != null)
                request.Headers.Add(header);
            if (credential != null)
                request.Credentials = credential;

            if (!string.IsNullOrEmpty(proxyAddress))
            {
                IWebProxy proxy = new WebProxy(proxyAddress);
                proxy.Credentials = new NetworkCredential();
                request.Proxy = proxy;
            }

            if (!string.IsNullOrEmpty(data))
            {
                using (var swt = new StreamWriter(request.GetRequestStream()))
                {
                    swt.Write(data);
                }
            }

            string result = string.Empty;
            using (WebResponse response = request.GetResponse())
            {
                if (response.ContentType.IndexOf("octet-stream") > -1)
                {
                    string dispositionStr = response.Headers["Content-Disposition"];
                    int fileNameI = dispositionStr.IndexOf("filename=");
                    string fileName = dispositionStr.Substring(fileNameI + 9, dispositionStr.Length - (fileNameI + 9));
                    fileName = HttpUtility.UrlDecode(fileName, Encoding.UTF8);
                    string downpath = AppDomain.CurrentDomain.BaseDirectory + "Download";
                    if (!Directory.Exists(downpath))
                    {
                        Directory.CreateDirectory(downpath);
                    }
                    string downFile = downpath + "\\" + fileName;

                    if (File.Exists(downFile))
                    {
                        File.Delete(downFile);
                    }
                    Stream inStream = response.GetResponseStream();
                    using (Stream outStream = File.OpenWrite(downFile))
                    {
                        byte[] buffer = new byte[8192];
                        int size = 0;
                        while ((size = inStream.Read(buffer, 0, 8192)) > 0)
                        {
                            outStream.Write(buffer, 0, size);
                        }
                    }
                    result = downFile;
                }
                else
                {
                    Stream stream = response.GetResponseStream();
                    if (responseEncoding == null) responseEncoding = Encoding.UTF8;
                    StreamReader myStreamReader = new StreamReader(stream, responseEncoding);
                    result = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    stream.Close();
                    //byte[] buf = new byte[1024];
                    //while (true)
                    //{
                    //    int len = stream.Read(buf, 0, buf.Length);
                    //    if (len <= 0)//len <= 0 跳出循环
                    //        break;
                    //    if (responseEncoding == null) responseEncoding = Encoding.UTF8;
                    //     result += responseEncoding.GetString(buf, 0, len);//指定编码格式
                    //}
                }
                //using (var sr = new StreamReader(response.GetResponseStream()))
                //{
                //    result = sr.ReadToEnd();
                //}
            }

            return result;
        }

        public static string WebClientRequest(string url, string method, 
            string contentType = "application/json", 
            NameValueCollection header = null, 
            string postString = "")
        {
            try
            {
                //创建WebClient 对象
                WebClient web = new WebClient();
                //以form表单的形式上传
                if (header != null)
                    web.Headers.Add(header);
                web.Headers.Add("Content-Type", contentType);
                // 转化成二进制数组0
                byte[] postData = Encoding.UTF8.GetBytes(postString);
                web.Headers.Add("ContentLength", postData.Length.ToString());
                if (Regex.IsMatch(url, "^https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidate);//验证服务器证书回调自动验证
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                }

                // 上传数据
                byte[] responseData = web.UploadData(url, method, postData);
                //获取返回的二进制数据.
                string ret = Encoding.UTF8.GetString(responseData);
                return ret;
            }
            catch (Exception e)
            {
                return "err_" + e.Message;
            }
        }

        /// <summary>
        /// HttpWebRequest发送文件
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="fileName">文件路径</param>
        /// <param name="fileParaName">文件参数名</param>
        /// <param name="contentType">contentType</param>
        /// <param name="nameValueCollection">其余要附带的参数键值对</param>
        public static string RequestUploadFile(string url, byte[] buffer, string fileParaName, string fileName, NameValueCollection nameValueCollection, string contentType = "application/octet-stream")
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;
            Stream requestStream = request.GetRequestStream();
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            if (nameValueCollection != null)
            {
                foreach (string key in nameValueCollection.Keys)
                {
                    requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    requestStream.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
            string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", fileParaName, fileName, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            requestStream.Write(headerbytes, 0, headerbytes.Length);
            //FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            //byte[] buffer = new byte[4096];
            //int bytesRead = 0;
            //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            //{
            //    requestStream.Write(buffer, 0, bytesRead);
            //}
            //fileStream.Close();
            requestStream.Write(buffer, 0, buffer.Length);
            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            requestStream.Write(trailer, 0, trailer.Length);
            requestStream.Close();
            WebResponse webResponse = null;
            try
            {
                webResponse = request.GetResponse();
                Stream responseStream = webResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream);
                string result = streamReader.ReadToEnd();
                return result;
            }
            catch (Exception ex)
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
            }
            finally
            {
                request = null;
            }
            return "";
        }

        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            //为了通过证书验证，总是返回true
            return true;
        }

        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;

            FileStream fs = null;
            try
            {

                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,

                FileShare.None);

                inUse = false;
            }
            catch
            {

            }
            finally
            {
                if (fs != null)

                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用
        }

        static List<string> ReadTxt2Lines()
        {
            List<string> lines = new List<string>();
            try
            {
                StreamReader sr = new StreamReader(TXT_PATH);
                string line = sr.ReadLine();
                while (line != null)
                {
                    lines.Add(line);
                    line = sr.ReadLine();
                }
                sr.Close();
            }
            catch (Exception e)
            {

            }
            return lines;
        }

        internal static bool deleteReqFromTxt(int index)
        {
            Boolean b = false;

            if (File.Exists(TXT_PATH) && index>=0)
            {
                List<string> lines = ReadTxt2Lines();
                if (lines.Count > 0)
                {
                    File.Delete(TXT_PATH);
                    lines.RemoveAt(index);
                    foreach(string line in lines)
                    {
                        Req req = line2Req(line);
                        if (req != null)
                        {
                            SaveReq2Text(req);
                        }
                    }
                }

            }
            return b;
        }

        private static Req line2Req(string line)
        {
            string[] vs = line.Split(',');
            if (vs.Length == 2)
            {
                Req req = new Req()
                {
                    url = vs[0],
                    param = vs[1],
                    method = "POST",
                    contType = "FORM"
                };
                return req;
            }
            return null;
        }
    }


    public class HttpHelper
    {
        /// <summary>
        /// 获取指定路径数据
        /// </summary>
        /// <param name="requestUri">提交路径</param>
        /// <param name="cookie">Cookie容器对象</param>
        /// <returns>字符串结果</returns>
        public static string GetForm(string requestUri, CookieContainer cookie)
        {
            HttpWebRequest request = WebRequest.CreateHttp(requestUri);
            request.Method = "get";
            request.CookieContainer = cookie;
            request.ContentLength = 0;

            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            return reader.ReadToEnd();
        }

        /// <summary>
        /// 默认表单提交
        /// </summary>
        /// <param name="requestUri">提交路径</param>
        /// <param name="postData">提交数据</param>
        /// <param name="cookie">Cookie容器对象</param>
        /// <returns>字符串结果</returns>
        public static string PostForm(string requestUri, NameValueCollection postData, CookieContainer cookie)
        {
            HttpWebRequest request = WebRequest.CreateHttp(requestUri);
            request.Method = "post";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = cookie;

            StringBuilder stringBuilder = new StringBuilder();
            foreach (string key in postData.Keys)
            {
                stringBuilder.AppendFormat("&{0}={1}", key, postData.Get(key));
            }
            byte[] buffer = Encoding.UTF8.GetBytes(stringBuilder.ToString().Trim('&'));
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            WebResponse response = request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            return reader.ReadToEnd();
        }

        /// <summary>
        /// 多部件表单提交
        /// </summary>
        /// <param name="requestUri">提交路径</param>
        /// <param name="postData">提交数据.注:如果是文件路径,代表是文件.</param>
        /// <param name="cookie">Cookie容器对象</param>
        /// <returns>字符串结果</returns>
        public static string PostFormMultipart(string requestUri, NameValueCollection postData, CookieContainer cookie)
        {
            string boundary = string.Format("-----{0}", DateTime.Now.Ticks.ToString("x"));
            HttpWebRequest webrequest = WebRequest.CreateHttp(requestUri);
            webrequest.CookieContainer = cookie;
            webrequest.Timeout = 120000;
            webrequest.Method = "post";
            webrequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

            Stream requestStream = webrequest.GetRequestStream();
            foreach (string key in postData.Keys)
            {
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.AppendFormat("--{0}", boundary);
                strBuilder.AppendFormat("\r\nContent-Disposition: form-data; name=\"{0}\"", key);
                if (File.Exists(postData.Get(key)))
                {
                    strBuilder.AppendFormat(";filename=\"{0}\"\r\nContent-Type: multipart/form-data\r\n\r\n", Path.GetFileName(postData.Get(key)));
                    byte[] buffer = Encoding.UTF8.GetBytes(strBuilder.ToString());
                    requestStream.Write(buffer, 0, buffer.Length);
                    //获取图片流
                    FileStream fileStream = new FileStream(postData.Get(key), FileMode.Open, FileAccess.Read);
                    BinaryReader binaryReader = new BinaryReader(fileStream);
                    byte[] fileBuffer = binaryReader.ReadBytes((int)fileStream.Length);
                    binaryReader.Close();
                    fileStream.Close();
                    requestStream.Write(fileBuffer, 0, fileBuffer.Length);
                }
                else
                {
                    strBuilder.AppendFormat("\r\n\r\n{0}\r\n", postData.Get(key));
                    byte[] buff = Encoding.UTF8.GetBytes(strBuilder.ToString());
                    requestStream.Write(buff, 0, buff.Length);
                }
            }

            byte[] boundaryBuffer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}\r\n", boundary));
            requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
            requestStream.Close();

            WebResponse response = webrequest.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
}
